package com.example.movie.ui.user.auth

import android.content.Intent
import android.os.Bundle
import android.text.*
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.activity.viewModels
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import com.example.movie.R
import com.example.movie.common.dsl.afterTextChanged
import com.example.movie.data.user.login.factory.LoginViewModelFactory
import com.example.movie.data.user.login.model.SharedLoginViewModel
import kotlinx.android.synthetic.main.fragment_register.*

class RegisterActivity : AppCompatActivity() {

    private  val registerViewModel: SharedLoginViewModel by viewModels(factoryProducer = { LoginViewModelFactory() })

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fragment_register)
        initRegisterForm()
    }

    private fun initRegisterForm() {
        back.setOnClickListener {
            onBackPressed()
        }

        register.setOnClickListener {
            registerViewModel.register(username.text.toString(), password.text.toString())
        }

        show_password.setOnClickListener {
            showOrHidePassword()
        }

        username_clear_btn.setOnClickListener {
            clearEditText(it)
        }

        password_clear_btn.setOnClickListener {
            clearEditText(it)
        }

        registerViewModel.loginFormState.observe(this, Observer {
            val loginState = it ?: return@Observer
            register.isEnabled = loginState.isDataValid
            if (loginState.usernameError != null) {
                username.error = getString(loginState.usernameError)
            }
            if (loginState.passwordError != null) {
                password.error = getString(loginState.passwordError)
            }
        })

        registerViewModel.registerResult.observe(this, Observer {
            val registerResult = it ?: return@Observer

            if (registerResult.error != null) {
                showRegisterFailed(registerResult.error)
            }
            if (registerResult.success != null) {
                Toast.makeText(this, "注册成功!", Toast.LENGTH_SHORT).show()
                startActivity(Intent(this, LoginActivity::class.java))
            }

        })

        username.apply {
            afterTextChanged {
                if (username.text.isEmpty()) {
                    username_clear_btn.visibility = View.GONE
                } else {
                    username_clear_btn.visibility = View.VISIBLE
                }
                registerViewModel.loginDataChanged(
                    username.text.toString(),
                    password.text.toString()
                )
            }

        }

        password.apply {
            afterTextChanged {
                if (password.text.isEmpty()) {
                    password_clear_btn.visibility = View.GONE
                } else {
                    password_clear_btn.visibility = View.VISIBLE
                }
                registerViewModel.loginDataChanged(
                    username.text.toString(),
                    password.text.toString()
                )
            }

            setOnEditorActionListener { _, actionId, _ ->
                when (actionId) {
                    EditorInfo.IME_ACTION_DONE ->
                        registerViewModel.login(
                            username.text.toString(),
                            password.text.toString()
                        )
                }
                false
            }
        }

    }

    private fun showRegisterFailed(@StringRes errorString: Int) {
        Toast.makeText(this, errorString, Toast.LENGTH_SHORT).show()
    }

    /**
     * 点击之后显示或者隐藏密码
     */
    private fun showOrHidePassword() {
        if (show_password.isChecked) {
            password.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
        } else {
            password.inputType =
                InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
        }

        // 设置光标到未能本末尾
        val charSequence: CharSequence = password.text
        if (charSequence is Spannable) {
            Selection.setSelection(charSequence, charSequence.length)
        }

    }


    /**
     * 清除编辑框信息
     */
    private fun clearEditText(view: View) {
        when (view.id) {
            R.id.username_clear_btn -> username.setText("")
            R.id.password_clear_btn -> password.setText("")
        }
    }
}

